/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Egresos;
import com.camachosanchez.bean.Pilotos;
import com.camachosanchez.reportes.bean.EgresosDetallado;
import com.camachosanchez.reportes.bean.EgresosResumido;
import com.camachosanchez.reportes.nuevos.NuevoReporteDetalladoEgresos;
import com.camachosanchez.reportes.nuevos.NuevoReporteResumidoEgresos;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.Query;

/**
 *
 * @author ZULLY
 */
public class DialogoReporteEgresos extends javax.swing.JDialog {

    /**
     * Creates new form DialogoReporteEgresos
     */
    public DialogoReporteEgresos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
//        setSize(250, 135);
        setLocationRelativeTo(null);
        GUIUtil.addEscapeKey(this);
        dateInicio.setMaxSelectableDate(new Date());
        dateFin.setMaxSelectableDate(new Date());
        dateInicio.setDate(new Date());
        dateFin.setDate(new Date());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlContenedor = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        cmbTipoReporte = new javax.swing.JComboBox();
        dateInicio = new com.toedter.calendar.JDateChooser();
        dateFin = new com.toedter.calendar.JDateChooser();
        jToolBar1 = new javax.swing.JToolBar();
        jPanel1 = new javax.swing.JPanel();
        btnGenerarReporte = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Egresos ::.");
        setResizable(false);

        pnlContenedor.setBackground(new java.awt.Color(231, 239, 247));

        jLabel3.setText("Fecha inicial:");

        jLabel2.setText("Fecha final:");

        jLabel1.setText("Tipo Reporte:");

        cmbTipoReporte.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Resumido", "Detallado" }));

        dateInicio.setDateFormatString("dd/MM/yyyy");
        dateInicio.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateInicioPropertyChange(evt);
            }
        });

        dateFin.setDateFormatString("dd/MM/yyyy");

        javax.swing.GroupLayout pnlContenedorLayout = new javax.swing.GroupLayout(pnlContenedor);
        pnlContenedor.setLayout(pnlContenedorLayout);
        pnlContenedorLayout.setHorizontalGroup(
            pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlContenedorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cmbTipoReporte, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dateInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dateFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pnlContenedorLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel2, jLabel3});

        pnlContenedorLayout.setVerticalGroup(
            pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlContenedorLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbTipoReporte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dateFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(dateInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3)))
                .addContainerGap())
        );

        getContentPane().add(pnlContenedor, java.awt.BorderLayout.CENTER);

        jToolBar1.setBackground(new java.awt.Color(255, 255, 255));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setMinimumSize(new java.awt.Dimension(63, 25));
        jToolBar1.setPreferredSize(new java.awt.Dimension(63, 30));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setMinimumSize(new java.awt.Dimension(69, 25));
        jPanel1.setPreferredSize(new java.awt.Dimension(383, 25));
        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));

        btnGenerarReporte.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/pdf.png"))); // NOI18N
        btnGenerarReporte.setText("Imprimir");
        btnGenerarReporte.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGenerarReporte.setContentAreaFilled(false);
        btnGenerarReporte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerarReporteActionPerformed(evt);
            }
        });
        jPanel1.add(btnGenerarReporte);

        jToolBar1.add(jPanel1);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGenerarReporteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarReporteActionPerformed
        // TODO add your handling code here:
        try {
            int tipoReporte = cmbTipoReporte.getSelectedIndex();
            List<String[]> listaEgresos = new ArrayList<String[]>();
            Calendar cal = Calendar.getInstance();
            cal.setTime(dateInicio.getDate());
            Calendar fechaIni = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
            cal.setTime(dateFin.getDate());
            Calendar fechaFin = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));

//            ReporteEgresos reporte = new ReporteEgresos();
            List<Egresos> egresos = getDatos(fechaIni.getTime(), fechaFin.getTime());
            BigDecimal montoLlantas = BigDecimal.valueOf(0);
            BigDecimal montoVigilante = BigDecimal.valueOf(0);
            BigDecimal totalLlantas = BigDecimal.valueOf(0);
            BigDecimal totalVigilante = BigDecimal.valueOf(0);
            if (!egresos.isEmpty()) {
                Integer idPiloto = egresos.get(0).getIdPilotos().getId();
                if (tipoReporte == 0) {
                    Pilotos piloto = egresos.get(0).getIdPilotos();
                    for (Egresos item : egresos) {
                        if (!item.getIdPilotos().getId().equals(idPiloto)) {
                            String[] egs = new String[4];
                            egs[0] = piloto.getApellidos() + " " + piloto.getNombres();
                            egs[1] = montoLlantas.toString();
                            egs[2] = montoVigilante.toString();
                            egs[3] = (montoLlantas.add(montoVigilante)).toString();
                            listaEgresos.add(egs);
                            montoLlantas = BigDecimal.valueOf(0);
                            montoVigilante = BigDecimal.valueOf(0);
                        }
                        if (item.getTipo() == Constantes.TIPO_LLANTAS) {
                            montoLlantas = montoLlantas.add(item.getMonto());
                            totalLlantas = totalLlantas.add(item.getMonto());
                        } else {
                            montoVigilante = montoVigilante.add(item.getMonto());
                            totalVigilante = totalVigilante.add(item.getMonto());
                        }

                        piloto = item.getIdPilotos();
                        idPiloto = item.getIdPilotos().getId();
                    }
                    String[] egs = new String[4];
                    egs[0] = piloto.getApellidos() + " " + piloto.getNombres();
                    egs[1] = montoLlantas.toString();
                    egs[2] = montoVigilante.toString();
                    egs[3] = (montoLlantas.add(montoVigilante)).toString();
                    listaEgresos.add(egs);
                    //--------------------
                    String[] total = new String[3];
                    total[0] = totalLlantas.toString();
                    total[1] = totalVigilante.toString();
                    total[2] = (totalLlantas.add(totalVigilante)).toString();
                    listaEgresos.add(total);
                    //--------------------
                    EgresosResumido egresosReporte = new EgresosResumido();
                    egresosReporte.setFechaDesde(GUIUtil.convertirFechaDDMMYYY(fechaIni.getTime()));
                    egresosReporte.setFechaHasta(GUIUtil.convertirFechaDDMMYYY(fechaFin.getTime()));
                    egresosReporte.setListaEgresos(listaEgresos);
                    NuevoReporteResumidoEgresos reporte = new NuevoReporteResumidoEgresos();
                    reporte.generarReporte(egresosReporte);
                    /*
                    Impresor impresor = new Impresor(egresosReporte);
                    Principal.getInstance().getEscritorio().add(impresor);
                    impresor.setVisible(true);
                    impresor.setMaximum(true);*/

                } else {
                    for (Egresos item : egresos) {
                        if (!item.getIdPilotos().getId().equals(idPiloto)) {
                            String[] subtotal = new String[4];
                            subtotal[0] = "2";//SUBTOTAL
                            subtotal[1] = montoLlantas.toString();
                            subtotal[2] = montoVigilante.toString();
                            subtotal[3] = (montoLlantas.add(montoVigilante)).toString();
                            listaEgresos.add(subtotal);
                            montoLlantas = BigDecimal.valueOf(0);
                            montoVigilante = BigDecimal.valueOf(0);
                        }
                        String[] egs = new String[6];
                        egs[0] = "1";//PILOTO
                        egs[1] = item.getIdPilotos().getApellidos() + " " + item.getIdPilotos().getNombres();
                        egs[5] = GUIUtil.convertirFechaDDMMYYY(item.getFecha());

                        egs[3] = (montoLlantas.add(montoVigilante)).toString();

                        if (item.getTipo() == Constantes.TIPO_LLANTAS) {
                            egs[2] = item.getMonto().toString();
                            egs[3] = "";
                            montoLlantas = montoLlantas.add(item.getMonto());
                            totalLlantas = totalLlantas.add(item.getMonto());
                        } else {
                            egs[2] = "";
                            egs[3] = item.getMonto().toString();
                            montoVigilante = montoVigilante.add(item.getMonto());
                            totalVigilante = totalVigilante.add(item.getMonto());
                        }
                        egs[4] = item.getMonto().toString();
                        listaEgresos.add(egs);
                        idPiloto = item.getIdPilotos().getId();
                    }
                    //agrega el último sub total
                    String[] subtotal = new String[4];
                    subtotal[0] = "2";//SUBTOTAL
                    subtotal[1] = montoLlantas.toString();
                    subtotal[2] = montoVigilante.toString();
                    subtotal[3] = (montoLlantas.add(montoVigilante)).toString();
                    listaEgresos.add(subtotal);

                    String[] total = new String[4];
                    total[0] = "3";//TOTAL
                    total[1] = totalLlantas.toString();
                    total[2] = totalVigilante.toString();
                    total[3] = (totalLlantas.add(totalVigilante)).toString();
                    listaEgresos.add(total);

                    //--------------------
                    EgresosDetallado egresosReporte = new EgresosDetallado();
                    egresosReporte.setFechaDesde(GUIUtil.convertirFechaDDMMYYY(fechaIni.getTime()));
                    egresosReporte.setFechaHasta(GUIUtil.convertirFechaDDMMYYY(fechaFin.getTime()));
                    egresosReporte.setListaEgresos(listaEgresos);

                    NuevoReporteDetalladoEgresos reporte = new NuevoReporteDetalladoEgresos();
                    reporte.generarReporte(egresosReporte);
                    /*
                    Impresor impresor = new Impresor(egresosReporte);
                    Principal.getInstance().getEscritorio().add(impresor);
                    impresor.setVisible(true);
                    impresor.setMaximum(true);*/
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnGenerarReporteActionPerformed

    private List<Egresos> getDatos(Date fechaIni, Date fechaFin) {
        java.sql.Date sqlFechaIni = new java.sql.Date(fechaIni.getTime());
        java.sql.Date sqlFechaFin = new java.sql.Date(fechaFin.getTime());
        Query q1 = JPAUtil.getEntityManagerFactory().createEntityManager().createQuery("SELECT E FROM Egresos E"
                + " WHERE E.fecha >= :fechaIni AND E.fecha <= :fechaFin AND E.anulado=0"
                + " ORDER BY E.idPilotos.apellidos, E.tipo DESC, E.fecha");
        q1.setParameter("fechaIni", sqlFechaIni);
        q1.setParameter("fechaFin", sqlFechaFin);
        return q1.getResultList();
    }

private void dateInicioPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateInicioPropertyChange
// TODO add your handling code here:
    if (evt.getPropertyName().compareTo("date") == 0) {
        dateFin.setMinSelectableDate(dateInicio.getDate());
    }
}//GEN-LAST:event_dateInicioPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGenerarReporte;
    private javax.swing.JComboBox cmbTipoReporte;
    private com.toedter.calendar.JDateChooser dateFin;
    private com.toedter.calendar.JDateChooser dateInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPanel pnlContenedor;
    // End of variables declaration//GEN-END:variables
}
